<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="dt">
        <el-date-picker clearable v-model="queryParams.dt" type="year" value-format="yyyy-MM-dd" placeholder="请选择年份" @change="handleQuery"></el-date-picker>
      </el-form-item>

      <el-form-item label="农户" prop="farmerName">
        <el-input v-model="queryParams.farmerName" placeholder="请输入农户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="销售区域" prop="saleArea">
        <el-select v-model="queryParams.saleArea" placeholder="请选择销售区域" clearable>
          <el-option v-for="dict in dict.type.sale_area" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售方式" prop="saleWay">
        <el-select v-model="queryParams.saleWay" placeholder="请选择销售方式" clearable>
          <el-option v-for="dict in dict.type.sale_way" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ap:order:add']">新增</el-button></el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['ap:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ap:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5"><el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['ap:order:export']">导出</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="日期" align="center" prop="dt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="农户" align="left" prop="farmerName" />
      <el-table-column label="收货人" align="left" prop="addressName" />
      <el-table-column label="联系电话" align="left" prop="addressTel" />
      <el-table-column label="详细地址" align="left" prop="addressDetail" />
      <el-table-column label="销售区域" align="center" prop="saleArea">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sale_area" :value="scope.row.saleArea" />
        </template>
      </el-table-column>
      <el-table-column label="销售方式" align="center" prop="saleWay">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sale_way" :value="scope.row.saleWay" />
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="right" prop="amount" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ap:order:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ap:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改销售单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="日期" prop="dt">
              <el-date-picker clearable v-model="form.dt" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- 下拉树形选择农户 -->
            <el-form-item label="农户" prop="farmerId">
              <treeselect v-model="form.farmerId" :options="farmerOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择农户" />
            </el-form-item>

          </el-col>
          <el-col :span="6">
            <el-form-item label="销售区域" prop="saleArea">
              <el-select v-model="form.saleArea" placeholder="请选择销售区域">
                <el-option v-for="dict in dict.type.sale_area" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售方式" prop="saleWay">
              <el-select v-model="form.saleWay" placeholder="请选择销售方式">
                <el-option v-for="dict in dict.type.sale_way" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="收货人" prop="addressName"><el-input v-model="form.addressName" placeholder="请输入收货人" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="addressTel"><el-input v-model="form.addressTel" placeholder="请输入联系电话" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="详细地址" prop="addressDetail"><el-input v-model="form.addressDetail" placeholder="请输入详细地址" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" placeholder="请输入备注" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="form.id != null" content-position="center">产品清单</el-divider>
      <el-card shadow="always" v-if="form.id != null" class="box-card"><OrderDetailList :orderId="form.id"></OrderDetailList></el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder, farmerTreeSelect } from '@/api/ap/order';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import OrderDetailList from './components/OrderDetailList.vue';
export default {
  name: 'Order',
  dicts: ['order_status', 'sale_way' ,'sale_area'],
  components: { Treeselect , OrderDetailList },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dt: null,
        farmerName: null,
        saleArea: null,
        saleWay: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dt: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
        farmerId: [{ required: true, message: '农户不能为空', trigger: 'blur' }],
        saleArea: [{ required: true, message: '销售区域不能为空', trigger: 'blur' }],
        saleWay: [{ required: true, message: '销售方式不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      },

      // 农户树选项
      farmerOptions: undefined,
    };
  },
  created() {
    this.getList();
    farmerTreeSelect().then(response => {
      this.farmerOptions = response.data;
    });
  },
  methods: {
    /** 查询销售单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dt: this.parseTime(new Date()),
        farmerId: null,
        addressName: null,
        addressTel: null,
        addressProvince: null,
        addressCity: null,
        addressCounty: null,
        addressDetail: null,
        areaCode: null,
        saleArea: null,
        saleWay: null,
        status: '1',
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加销售单';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改销售单';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              console.log(response)
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除销售单编号为"' + ids + '"的数据项？')
        .then(function() {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'ap/order/export',
        {
          ...this.queryParams
        },
        `order_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
